package com.functest.orm

import groovy.sql.Sql

/**
 * Created with IntelliJ IDEA.
 * User: MalyutinAA
 * Date: 10.07.13
 * Time: 16:59
 * To change this template use File | Settings | File Templates.
 */
class TestDataForCalculatedFields {
    final static Sql dataBase
    static {
        Class.forName('org.sqlite.JDBC');
    }

    static class Numbers{
        int num
        String firstText
        String lastText


        Numbers(int num, String firstText, String lastText){
            this.num = num
            this.firstText = firstText
            this.lastText = lastText

        }

        static SingleDbTableMapper<Numbers> numbers_mapper =
            new SingleDbTableMapper<Numbers>(
                    new MapperFields().with {
                        field('num')
                        field('firstText','first_text')
                        field(  'lastText',
                                ['num','first_text'],
                                { Field f, Map m -> (m['first_text'] + '_' + m['num'].toString()) } as Closure,
                                { Field f, def value -> [num: (value as String).split('_').last() as int, first_text: (value as String).split('_').first()] } as Closure
                        )
                        delegate as MapperFields
                    }
                    , { TestDataForCalculatedFields.dataBase }
                    , 'numbers'
                    , 'num'
                    , Numbers
            )

        static BaseProvider<Numbers> provider = new BaseProvider<Numbers>(Numbers, [numbers_mapper])

        Numbers(Map params) {
            for (Map.Entry entry in params.entrySet()) {
                if (entry.value != null) {
                    this."${entry.key }" = entry.value
                }
            }
        }
    }

    static{
        dataBase = Sql.newInstance('jdbc:sqlite::memory:', 'org.sqlite.SQLite')
        dataBase.with{
            execute("create table numbers (num int, first_text text)")
            execute("insert into numbers values(2,'word')")
            execute("insert into numbers values(5,'text')")
        }
    }

}
